package com.zyk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zyk.entity.Organization;
import com.zyk.entity.Role;
import com.zyk.entity.User;
import com.zyk.mapper.OrganizationMapper;
import com.zyk.mapper.RoleMapper;
import com.zyk.mapper.UserMapper;
import com.zyk.mapper.UserRoleMapper;
import com.zyk.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zyk.vo.DataGridVo;
import com.zyk.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author feifeimao
 * @since 2017-11-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RoleMapper roleMapper;
    

    @Autowired
    private OrganizationMapper organizationMapper;

    public DataGridVo dataGrid() {
        List<User> users = super.selectList(new EntityWrapper<User>(null));
        List<UserVo> userVos= new ArrayList<UserVo>();
        for (User user: users) {
            UserVo userVo= new UserVo();
            Organization or = organizationMapper.selectById(user.getOrganizationId());
            List<Role> roles = roleMapper.selectRoleIdListByUserId(user.getId());
            //防止没有权限的用户发生空指针异常
            if(roles.size()!=0){
                String rolesList=null;
                for (Role role:roles) {
                    rolesList=rolesList+","+role.getName();
                }
                String substring = rolesList.substring(5, rolesList.length());
                userVo.setRolesList(substring.toString());
            }
            BeanUtils.copyProperties(user,userVo);
            userVo.setId(user.getId());
            userVo.setOrganizationId(user.getOrganizationId());
            userVo.setOrganizationName(or.getName());
            userVos.add(userVo);
        }
        return new DataGridVo(userVos.size(),userVos);
    }
}
